package com.chinatechstar.component.commons.utils;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.chinatechstar.component.commons.constants.HttpConstants;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务调用工具类
 *
 * @author Rei
 */
public class HttpClientUtils {
    private static final String CHARSET = "UTF-8";

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);

    public static String doGet(String url, Map<String, String> param) throws Exception {
        String resultString = "";
        CloseableHttpResponse response = null;
        try (
                // 创建Httpclient对象
                CloseableHttpClient httpclient = HttpClients.createDefault();
        ) {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {

                Set<Map.Entry<String, String>> entries = param.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            // 执行请求
            response = httpclient.execute(httpGet);

            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), CHARSET);
            }
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }
        return resultString;
    }

    public static String doGet(String url) throws Exception {
        return doGet(url, null);
    }

    public static String doPost(String url, Map<String, String> param) {
        CloseableHttpResponse response = null;
        String resultString = "";
        try (
                // 创建Httpclient对象
                CloseableHttpClient httpClient = HttpClients.createDefault();
        ) {
            // 创建Http Post请求
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setHeader("Connection", "Keep-Alive");
            httpPost.setHeader("Charset", CHARSET);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }

                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, CHARSET);
                httpPost.setEntity(entity);
            }

            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null);
    }

    public static String doPostJson(String url, JSONObject jsonObject) {
        return doPostJson(url, jsonObject.toString());
    }

    public static String doPostJson(String url, String json) {

        CloseableHttpResponse response = null;
        String resultString = "";
        try (
                // 创建Httpclient对象
                CloseableHttpClient httpClient = HttpClients.createDefault();
        ) {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), CHARSET);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("", e);
            }
        }

        return resultString;
    }

    /**
     * 通过http访问获取json数据
     *
     * @param targetURL url
     * @return String
     * @throws IOException io
     */
    public static String getJsonString(String targetURL) throws IOException {
        String res = "";
        StringBuilder buffer = new StringBuilder();
        URL url = new URL(targetURL);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        if (200 == urlCon.getResponseCode()) {
            InputStream is = urlCon.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader br = new BufferedReader(isr);

            String str;
            while ((str = br.readLine()) != null) {
                buffer.append(str);
            }
            br.close();
            isr.close();
            is.close();
            res = buffer.toString();
        }
        return res;
    }

    /**
     * 测试URL是否能够访问
     *
     * @param urlString URL
     * @return boolean
     */
    public static boolean testUrl(String urlString) {
        URL url;
        try {
            url = new URL(urlString);
            url.openStream();
            return true;
        } catch (Exception e1) {
            return false;
        }
    }

    /**
     * 测试URL在限制时间内是否能够访问
     *
     * @param urlString          URL
     * @param timeOutMillSeconds 限制时间
     */
    public static boolean testUrlWithTimeOut(String urlString, int timeOutMillSeconds) {
        URL url;
        try {
            url = new URL(urlString);
            URLConnection co = url.openConnection();
            co.setConnectTimeout(timeOutMillSeconds);
            co.connect();
            return true;
        } catch (Exception e1) {
            return false;
        }
    }

    public static Map<String, String> getA2ReqParam() {
        Map<String, String> map = new HashMap<>();
        map.put("strUserName", HttpConstants.STR_USER_NAME);
        map.put("strPassword", HttpConstants.STR_PASSWORD);
        map.put("modename", HttpConstants.MODE_NAME);
        map.put("systemName", HttpConstants.SYSTEM_NAME);
        map.put("subSystemUser", HttpConstants.SUB_SYSTEM_USER);
        return map;
    }


    public static void main(String[] args) {

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("id", 1000012342378L);
        JSONObject data = new JSONObject();
        data.put("mode", "sync");
        data.put("terminals", 333);
        JSONObject content = new JSONObject();
        content.put("id", "1");
        content.put("l1", "333");
        content.put("l2", "333");
        content.put("l3", "333");
        data.put("content", content);
        jsonObject.put("data", data);

        Map<String, String> map = getA2ReqParam();
//        map.put("sql", " SELECT * FROM EPDMX.OP_PROD_WELL_PROD_DAILY where PROD_DATE =  to_date('20210505', 'yyyymmdd') AND rownum < 11");
//        map.put("sql", "SELECT * FROM EPDMX.OP_PROD_WELL_PROD_DAILY WHERE PROD_DATE BETWEEN to_date('20210501', 'yyyymmdd') AND to_date('20210505', 'yyyymmdd') AND rownum < 2");
        map.put("sql", "SELECT * FROM EPDMX.OP_PROD_WELL_PROD_DAILY WHERE PROD_DATE BETWEEN to_date('20171201', 'yyyymmdd') AND to_date('20171231', 'yyyymmdd') AND WELL_ID = 'DG9UONHQuH' ");


        System.out.println(map);
        String s = HttpClientUtils.doPost(HttpConstants.A2_HOST + HttpConstants.A2_URL, map);
        System.out.println(s);

        Map<String, String> res = new HashMap<>();
        Map<String, Map<String, String>> res2 = new HashMap<>();
        XmlUtils.parseXml2Map(s, res);
        List<Map<String, String>> list = XmlUtils.parseA2Xml2Map(s, HttpConstants.FILED_OP_PROD_WELL_PROD_DAILY);
        System.out.println(list);

        for (Map<String, String> e : list) {
            for (String field : HttpConstants.FILED_OP_PROD_WELL_PROD_DAILY) {
                System.out.println(e.get(field));
            }
        }


        long periodOfLocalDate = DateUtils.getPeriodOfLocalDate(LocalDate.of(2017, 1, 1), LocalDate.of(2017, 12, 31));
        System.out.println(periodOfLocalDate);
    }

}
